package com.example.queues_mode;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文本审核测试
 *
 */
@Slf4j
@SpringBootTest
public class TextAudit {
    /**
     * 拿到密钥
     */
    @Value("${spring.baidu.apiKey}")
    private String apiKey;
    @Value("${spring.baidu.secretKey}")
    private String secretKey;
    /**
     * 文本审核测试
     */
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    @Test
    public void test() throws IOException {
        /**
         * 获取token
         */
        String urlGet="grant_type=client_credentials&client_id=%s"+"&client_secret=%s";
        String content = String.format(urlGet,apiKey, secretKey);
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType,content);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        String accessToken = jsonObject.getString("access_token");
        log.info("结果集:{}",accessToken);
        /**
         * 文本审核
         */
        String text="赌博及高利贷";
        MediaType mediaType1 = MediaType.parse("application/x-www-form-urlencoded");
        String param = "text=" + URLEncoder.encode(text, "utf-8");
        RequestBody body1 = RequestBody.create(mediaType1, param);
        Request request1 = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token="+accessToken)
                .method("POST", body1)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response1 = HTTP_CLIENT.newCall(request1).execute();
        log.info("文本审核:{}",text);
        System.out.println(response1.body().string());

    }
}
